package com.hinner.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hinner.entity.SysMenu;
import com.hinner.entity.SysRole;
import com.hinner.entity.SysUser;
import com.hinner.mapper.SysMenuMapper;
import com.hinner.mapper.SysRoleMapper;
import com.hinner.mapper.SysUserMapper;
import com.hinner.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public SysUser getUserByUserName(String username) {
        return this.getOne(new QueryWrapper<SysUser>().eq("username", username));
    }

    /**
     * 用户详情：要拿到某个用户的角色信息、每个角色拥有的菜单权限信息
     * @param userId
     * @return
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {
        StringBuffer sb = new StringBuffer();
        //1. 用户角色信息
        List<SysRole> roles = sysRoleMapper.selectList(new QueryWrapper<SysRole>().inSql("id", "SELECT role_id from sys_user_role where user_id = " + userId));
        if (CollectionUtil.isNotEmpty(roles)){
            // 只要角色信息表的code字段,并拼接成Role_admin,Role_user的格式
            String rolesStr = roles.stream().map(sysRole -> "ROLE_" + sysRole.getCode()).collect(Collectors.joining(","));
            sb.append(rolesStr);
        }
        //2. 角色关联的菜单权限信息，不能重复
        Set<String> set = new HashSet<>();
        for (SysRole role : roles) {
            List<SysMenu> menuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().inSql("id", "SELECT menu_id from sys_role_menu where role_id = " + role.getId()));
            // 要菜单表的 perms字段,且不能重复（遍历时就要放到set集合中）
            if (CollectionUtil.isNotEmpty(menuList)){
                menuList.forEach(sysMenu -> {
                    if (StrUtil.isNotEmpty(sysMenu.getPerms())){
                        set.add(sysMenu.getPerms());
                    }
                });
            }
        }
        // 整理set集合，每个字段用逗号隔开
        if (CollectionUtil.isNotEmpty(set)){
            sb.append(",");
            String menusStr = set.stream().collect(Collectors.joining(","));
            sb.append(menusStr);
        }

        return sb.toString();
    }
}
